//
//  SocketManager.m
//  JiuLe
//
//  Created by xcq on 15/12/8.
//  Copyright © 2015年 Fine. All rights reserved.
//
#import "Costants.h"
#import "Common.h"
#import "UserDataMarco.h"
#import "SVProgressHUD.h"
#import "SocketManager.h"
#import "JlUserManager.h"

#define DEFINE_SHARED_INSTANCE_USING_BLOCK(block) \
static dispatch_once_t onceToken = 0; \
__strong static id sharedInstance = nil; \
dispatch_once(&onceToken, ^{ \
sharedInstance = block(); \
}); \
return sharedInstance; \

static const Byte CLOCK_SETTING[1] = {0x01};
static const Byte SET_LINE_SETTING[1] = {0x02};
static const Byte ACTIVITY_VALUE[1] = {0x03};

static const Byte startByte[2] = {0x5a,0x5a};
static const Byte SAddress[1] = {0x02};
static const Byte DAddress[1] = {0x03};
static const Byte mTotalNum[2] = {0x00, 0x01};
static const Byte mNum[2] = {0x00, 0x01};


@implementation SocketManager
+(SocketManager *) sharedInstance
{
    static SocketManager *sharedInstace = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstace = [[self alloc] init];
    });
    return sharedInstace;
}

- (void)socketConnectHost {
    self.socket    = [[AsyncSocket alloc] initWithDelegate:self];
    NSError *error = nil;
//    if(![self.socket isDisconnected]) {
//        [self.socket disconnect];

//    } else {
//        [self.socket connectToHost:self.socketHost onPort:self.socketPort withTimeout:10 error:&error];
//    }
}

- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err {
    if (err != nil) {
        [self cutOffSocket];
    }
//    self.socket
    
}

- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port{
    NSLog(@"socket连接成功");
    
    [self.socket readDataWithTimeout:-1 tag:1];
    [JlUserManager shareInstance].socketManager = self;
}

- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag{
    NSLog(@"message did write");
    [self.socket readDataWithTimeout:-1 tag:tag];
}

- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
    NSLog(@"did read data");
    [self.socket readDataWithTimeout:-1 tag:tag];
    NSString *str = [self hexStringFromData:data];
    NSString *tagStr = [str substringWithRange:NSMakeRange(13, 1)];
    switch ([tagStr intValue]) {
        case 1:
        case 2: {
            NSString *dataStr = [str substringWithRange:NSMakeRange(17, 1)];
            if (dataStr.integerValue == 1) {
                [SVProgressHUD showSuccessWithStatus:@"设置成功"];
                BOOL isBol = [[NSUserDefaults standardUserDefaults] boolForKey:JiuLeOfflineMode];
                if (!isBol) {
                    if ([tagStr intValue] == 1) {
                        [[NSUserDefaults standardUserDefaults] setBool:YES
                                                                forKey:UserSetWatchAlarmData];
                    } else {
                        [[NSUserDefaults standardUserDefaults] setBool:YES
                                                                forKey:UserSetWatchValveData];
                    }
                }
                
            } else {
                [SVProgressHUD showSuccessWithStatus:@"设置失败"];
            }
        }//0000000c0000223801a3
             
            break;
        case 3: {
            //28 取 4个
            NSString *activity = [str substringWithRange:NSMakeRange(28, 4)];
            UInt64 activityint = strtoul([activity UTF8String], 0, 16);
            // 32
            NSString *caluli = [str substringWithRange:NSMakeRange(32, 4)];
            UInt64 caluliInt = strtoul([caluli UTF8String], 0, 16);
            // 36
            NSString *xueyang = [str substringWithRange:NSMakeRange(36, 2)];
            UInt64 xueyangInt = strtoul([xueyang UTF8String], 0, 16);
            // 38
            NSString *xinlv = [str substringWithRange:NSMakeRange(38, 2)];
            UInt64 xinlvInt = strtoul([xinlv UTF8String], 0, 16);
            // 40
            NSString *smlv = [str substringWithRange:NSMakeRange(40, 4)];
            UInt64 smInt = strtoul([smlv UTF8String], 0, 16);
            
            postNotificationWithObject(GetDataFromWatch, (@[@(activityint),@(caluliInt),@(xueyangInt),@(xinlvInt),@(smInt)]));
        }
    }
    
}

- (NSNumber *)convertHexArrToUInt:(NSArray *)arr {
    NSString *str = [NSString stringWithFormat:@"%@%@%@%@",arr[0],arr[1],arr[2],arr[3]];
    UInt64 countxx = strtoul([str UTF8String], 0, 16);
    NSNumber *number = [NSNumber numberWithUnsignedLongLong:countxx];
    return number;
}




- (void)wirteData:(NSData *)data andTag:(NSInteger)index{
    [self.socket writeData:data withTimeout:1 tag:index];
}

- (void)writeAlarmClock:(NSArray *)dates {
    Byte ValidByte[1] = {0x00};
    NSUInteger Length = 0;
    NSTimeInterval timestamp = [[NSDate new] timeIntervalSince1970];
    NSString *TimeString = [NSString stringWithFormat:@"%@",[[NSString alloc] initWithFormat:@"%1lx",(long)timestamp]];
    NSMutableData *timestampData = [self stringToByte:TimeString];
    NSMutableData *dateData = [[NSMutableData alloc]init];
    NSMutableData *data = [[NSMutableData alloc] initWithBytes:startByte length:2];
    [data appendBytes:SAddress length:1];
    [data appendBytes:DAddress length:1];
    
    NSDateFormatter *dateForMatter = [[NSDateFormatter alloc] init];
    [dateForMatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    [dateForMatter setTimeZone:[NSTimeZone localTimeZone]];
    NSString *dateStr = [dateForMatter stringFromDate:[NSDate date]];
    dateStr = [[dateStr componentsSeparatedByString:@" "] firstObject];
    for (int i = 0; i < dates.count; i++) {
        NSString *interval = [dates objectAtIndex:i];
        NSString *tempStr = [[dateStr stringByAppendingString:@" "] stringByAppendingString:[NSString stringWithFormat:@"%@",interval]];
        NSDate *currenDate = [dateForMatter dateFromString:tempStr];

        
        NSInteger timeInterval = [currenDate timeIntervalSince1970];
        NSString *hexString = [NSString stringWithFormat:@"%@",[[NSString alloc] initWithFormat:@"%1lx",(long)timeInterval]];
        NSData *temp = [SocketManager dataWithHexString:hexString];
        [dateData appendData:temp];
    }
    
    Length = 1 + 2 + 2 + dateData.length;
    NSString *hexString = [NSString stringWithFormat:@"%@",[[NSString alloc] initWithFormat:@"%1lx",(unsigned long)Length]];
    //0x00
    NSMutableData *ValidData = [NSMutableData dataWithBytes:ValidByte length:1];
    //0011
    [ValidData appendData:[self stringToByte:hexString]];
    [data appendData:ValidData];
    [data appendBytes:CLOCK_SETTING length:1];
    [data appendBytes:mTotalNum length:2];
    [data appendBytes:mNum length:2];
    [data appendData:dateData];
    [data appendData:timestampData];

    int sum = 0;
    Byte *bt = [data bytes];
    for (int i = 0 ; i < data.length; i ++) {
        NSString *a11 = [NSString stringWithFormat:@"%02x",*(bt+i)];
        UInt64 mac1 =  strtoul([a11 UTF8String], 0, 16);
        sum += mac1;
    }
    NSString *hexStringTemp = [NSString stringWithFormat:@"%@",[[NSString alloc] initWithFormat:@"%1x",sum]];
    if (hexStringTemp.length > 2) {
        hexStringTemp = [hexStringTemp substringWithRange:NSMakeRange(1, 2)];
    }
    NSData *dataCount = [SocketManager dataWithHexString:hexStringTemp];
    [data appendData:dataCount];
    [self wirteData:data andTag:0];
}

- (void)writeThresholdsSetDxl:(int)dxl gxy:(int)gxy xy:(int)xy {
    int commandLen = 6;
    NSUInteger totalLength = 1 + 2 + 2 + commandLen;
    Byte ValidByte[2] = {0x00,0xb};
    NSMutableData *data = [NSMutableData new];
    //0x00
    NSMutableData *ValidData = [NSMutableData dataWithBytes:ValidByte length:2];
    
    //dxl
    NSString *dxlString = [NSString stringWithFormat:@"%@",[[NSString alloc] initWithFormat:@"%1x",dxl]];
    if (dxlString.length == 3) {
        dxlString = [@"0" stringByAppendingString:dxlString];
    } else if (dxlString.length == 1) {
        dxlString = [@"000" stringByAppendingString:dxlString];
    } else if (dxlString.length == 2) {
        dxlString = [@"00" stringByAppendingString:dxlString];
    }
    NSMutableData *dxlData = [self stringToByte:dxlString];
   
    //gxy
    NSString *gxyString = [NSString stringWithFormat:@"%@",[[NSString alloc] initWithFormat:@"%1x",gxy]];
    if (gxyString.length == 3) {
        gxyString = [@"0" stringByAppendingString:gxyString];
    } else if (gxyString.length == 1) {
        gxyString = [@"000" stringByAppendingString:gxyString];
    } else if (gxyString.length == 2) {
        gxyString = [@"00" stringByAppendingString:gxyString];
    }
    NSMutableData *gxyData = [self stringToByte:gxyString];

    //xy
    NSString *xyString = [NSString stringWithFormat:@"%@",[[NSString alloc] initWithFormat:@"%1x",xy]];
    if (xyString.length == 3) {
        xyString = [@"0" stringByAppendingString:xyString];
    } else if (xyString.length == 1) {
        xyString = [@"000" stringByAppendingString:xyString];
    } else if (xyString.length == 2) {
        xyString = [@"00" stringByAppendingString:xyString];
    }
    NSMutableData *xyData = [self stringToByte:xyString];
    
    //时间戳
    NSTimeInterval timestamp = [[NSDate new] timeIntervalSince1970];
    NSString *TimeString = [NSString stringWithFormat:@"%@",[[NSString alloc] initWithFormat:@"%1lx",(long)timestamp]];
    NSMutableData *timestampData = [self stringToByte:TimeString];

    [data appendBytes:startByte length:2];
    [data appendBytes:SAddress length:1];
    [data appendBytes:DAddress length:1];
    [data appendData:ValidData];
    [data appendBytes:SET_LINE_SETTING length:1];
    [data appendBytes:mTotalNum length:2];
    [data appendBytes:mNum length:2];
    [data appendData:dxlData];
    [data appendData:gxyData];
    [data appendData:xyData];
    [data appendData:timestampData];
    
    int sum = 0;
    Byte *bt = [data bytes];
    for (int i = 0 ; i < data.length; i ++) {
        NSString *a11 = [NSString stringWithFormat:@"%02x",*(bt+i)];
        UInt64 mac1 =  strtoul([a11 UTF8String], 0, 16);
        sum += mac1;
    }
    NSString *hexStringTemp = [NSString stringWithFormat:@"%@",[[NSString alloc] initWithFormat:@"%1x",sum]];
    if (hexStringTemp.length > 2) {
        hexStringTemp = [hexStringTemp substringWithRange:NSMakeRange(1, 2)];
    }
    NSData *dataCount = [SocketManager dataWithHexString:hexStringTemp];
    [data appendData:dataCount];
    [self wirteData:data andTag:1];
}

- (void)writeActiveGet {
    //时间戳
    NSTimeInterval timestamp = [[NSDate new] timeIntervalSince1970];
    NSString *TimeString = [NSString stringWithFormat:@"%@",[[NSString alloc] initWithFormat:@"%1lx",(long)timestamp]];
    NSMutableData *timestampData = [self stringToByte:TimeString];

    NSMutableData *data = [NSMutableData new];
    [data appendBytes:startByte length:2];
    [data appendBytes:SAddress length:1];
    [data appendBytes:DAddress length:1];
    Byte ValidByte[2] = {0x00,0xA};
    [data appendBytes:ValidByte length:2];
    [data appendBytes:ACTIVITY_VALUE length:1];
    [data appendBytes:mTotalNum length:2];
    [data appendBytes:mNum length:2];
    [data appendData:timestampData];
    
    int sum = 0;
    Byte *bt = [data bytes];
    for (int i = 0 ; i < data.length; i ++) {
        NSString *a11 = [NSString stringWithFormat:@"%02x",*(bt+i)];
        UInt64 mac1 =  strtoul([a11 UTF8String], 0, 16);
        sum += mac1;
    }
    NSString *hexStringTemp = [NSString stringWithFormat:@"%@",[[NSString alloc] initWithFormat:@"%1x",sum]];
    NSData *dataCount = [SocketManager dataWithHexString:hexStringTemp];
    [data appendData:dataCount];
    [self wirteData:data andTag:2];
}

//data转换为十六进制的。
- (NSString *)hexStringFromData:(NSData *)myD{
    
    Byte *bytes = (Byte *)[myD bytes];
    //下面是Byte 转换为16进制。
    NSString *hexStr=@"";
    for(int i=0;i<[myD length];i++)
        
    {
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16进制数
        
        if([newHexStr length]==1)
            
            hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
        
        else
            
            hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
    }
    NSLog(@"%@",hexStr);
    
    return hexStr;
}

- (NSMutableData*)stringToByte:(NSString*)string
{
    NSString *hexString=[[string uppercaseString] stringByReplacingOccurrencesOfString:@" " withString:@""];
    if ([hexString length]%2!=0) {
        return nil;
    }
    Byte tempbyt[1]={0};
    NSMutableData* bytes=[NSMutableData data];
    for(int i=0;i<[hexString length];i++)
    {
        unichar hex_char1 = [hexString characterAtIndex:i]; ////两位16进制数中的第一位(高位*16)
        int int_ch1;
        if(hex_char1 >= '0' && hex_char1 <='9')
        int_ch1 = (hex_char1-48)*16;   //// 0 的Ascll - 48
        else if(hex_char1 >= 'A' && hex_char1 <='F')
        int_ch1 = (hex_char1-55)*16; //// A 的Ascll - 65
        else
        return nil;
        i++;
        
        unichar hex_char2 = [hexString characterAtIndex:i]; ///两位16进制数中的第二位(低位)
        int int_ch2;
        if(hex_char2 >= '0' && hex_char2 <='9')
        int_ch2 = (hex_char2-48); //// 0 的Ascll - 48
        else if(hex_char2 >= 'A' && hex_char2 <='F')
        int_ch2 = hex_char2-55; //// A 的Ascll - 65
        else
        return nil;
        
        tempbyt[0] = int_ch1+int_ch2;  ///将转化后的数放入Byte数组里
        [bytes appendBytes:tempbyt length:1];
    }
    return bytes;
}

+ (NSData *)dataWithHexString:(NSString *)hexStr {
    hexStr = [hexStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    hexStr = [hexStr lowercaseString];
    NSUInteger len = hexStr.length;
    if (!len) return nil;
    unichar *buf = malloc(sizeof(unichar) * len);
    if (!buf) return nil;
    [hexStr getCharacters:buf range:NSMakeRange(0, len)];
    NSMutableData *result = [NSMutableData data];
    unsigned char bytes;
    char str[3] = { '\0', '\0', '\0' };
    int i;
    for (i = 0; i < len / 2; i++) {
        str[0] = buf[i * 2];
        str[1] = buf[i * 2 + 1];
        bytes = strtol(str, NULL, 16);
        [result appendBytes:&bytes length:1];
    }
    free(buf);
    return result;
}

//重联
-(void)onSocketDidDisconnect:(AsyncSocket *)sock
{
    NSLog(@"sorry the connect is failure %ld",sock.userData);
    if (sock.userData == SocketOfflineByServer) {
        // 服务器掉线，重连
        [self socketConnectHost];
    }
    else if (sock.userData == SocketOfflineByUser) {
        // 如果由用户断开，不进行重连
        return;
    }
    
}

//切断
-(void)cutOffSocket{
    
    self.socket.userData = SocketOfflineByUser;// 声明是由用户主动切断
    
    [self.socket disconnect];
}

@end
